import uuid
from django.db import models
from django.core.exceptions import ValidationError

"""
Django 数据库迁移命令: 
python manage.py makemigrations
python manage.py migrate
.venv\Scripts\activate
"""


# 用户模型
class User(models.Model):
    uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    username = models.CharField(max_length=255, verbose_name='用户名')
    account = models.CharField(max_length=255, unique=True, verbose_name='账号')
    password = models.CharField(max_length=255, verbose_name='密码')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    def __str__(self):
        return self.username
    
    def clean(self):
        # 账号验证：只能是纯数字，长度在8-11位之间
        if self.account:
            if not self.account.isdigit():
                raise ValidationError({'account': '账号必须为纯数字'})
            if not 8 <= len(self.account) <= 11:
                raise ValidationError({'account': '账号长度必须在8-11位之间'})
        
        # 调用父类的clean方法
        super().clean()
    
    def save(self, *args, **kwargs):
        # 在保存前进行验证
        self.full_clean()
        super().save(*args, **kwargs)
    
    class Meta:
        verbose_name = '用户'
        verbose_name_plural = '用户'
        db_table = 'user'
        ordering = ['-created_at']